package com.imooc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.imooc.api.intercept.JWTCurrentUserInterceptor;
import com.imooc.base.BaseInfoProperties;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.pojo.Admin;
import com.imooc.pojo.bo.AdminBO;
import com.imooc.pojo.vo.AdminVO;
import com.imooc.service.AdminService;
import com.imooc.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.UUID;

/**
 * @author 啊昌
 * @date 2025/9/18 20:45
 * AdminController 管理员后台登录
 */
@RestController
@Slf4j
@RequestMapping("admin")
public class AdminController  extends BaseInfoProperties {

	@Autowired
	private AdminService adminService;

	@Autowired
	private JWTUtils jwtUtils;


	/**
	 * 管理员登录接口
	 * @param adminBO 管理员登录信息对象，包含用户名和密码等信息
	 * @return GraceJSONResult 登录结果，成功时返回管理员token，失败时返回错误信息
	 */
	@PostMapping("login")
	public GraceJSONResult login(@Valid @RequestBody AdminBO adminBO) {
		// 根据用户名查询管理员信息
		Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("username", adminBO.getUsername()));
		// 管理员用户不存在
		if(admin == null ){
			return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
		}

		// 验证管理员登录信息
		boolean b = adminService.adminLogin(adminBO);
		if(!b){
			return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
		}

		// 获取管理员完整信息并生成token
		Admin adminInfo = adminService.getAdminInfo(adminBO);
		String adminToken = jwtUtils.createJWTWithPrefix(new Gson().toJson(adminInfo),
				TOKEN_ADMIN_PREFIX);

		return GraceJSONResult.ok(adminToken);
	}


	@GetMapping("info")
	public GraceJSONResult info() {

		Admin admin = JWTCurrentUserInterceptor.adminUser.get();

		AdminVO adminVO = new AdminVO();
		BeanUtils.copyProperties(admin, adminVO);

		return GraceJSONResult.ok(adminVO);
	}

	@PostMapping("logout")
	public GraceJSONResult logout() {
		return GraceJSONResult.ok();
	}

}
